package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Stream;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;


    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;


    //会员折线图
    //{"flag":true,"message":"",data:{"months":[],"memberCount":[]}}
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){

        //存放最近一年的日期
        String[] months = new String[12];

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        for(int i=months.length-1; i>=0; i--){
           months[i]= sdf.format(calendar.getTime());
           calendar.add(Calendar.MONTH,-1);
        }


        //根据最近一年的日期，查询对应的会员数
       List<Integer> memberCount= memberService.findMemberCountByMonth(months);



        Map map =new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memberCount);

        return new Result(true,"查询成功",map);

    }


    //套餐饼图
    //{"flag":true,"message":"",data:{"setmealNames":"[粉红珍爱","入职无忧","阳光爸妈"],"setmealCount":[{name:"粉红珍爱",value:200},{name:"入职无忧",value:100},{name:"阳光爸妈",value:200}]}}
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){

        try {
            List<Map> list = setmealService.getSetmealOrderCount();
            List<String> setmealNames = new ArrayList<>();   //存放套餐的名称

            list.stream().forEach(m -> {                      //获取套餐名称存入setmealNames中
                setmealNames.add((String) m.get("name"));
            });


            Map map = new HashMap();
            map.put("setmealCount", list);
            map.put("setmealNames", setmealNames);

            return new Result(true,"套餐查询成功",map);
        }catch(Exception ex){
            ex.printStackTrace();
            return  new Result(false,"查询失败");
        }


    }

    //运营数据统计
    @GetMapping("/getBusinessReportData")
    public Result getBusinessData(){

        try {
            Map<String, Object> map = reportService.getBusinessData();
            return  new Result(true,"成功",map);
        }catch (Exception ex){
            ex.printStackTrace();
            return new Result(false,"失败");
        }






//        Map map = new HashMap();
//        map.put("reportDate","2021-12-06");
//        map.put("todayNewMember",900);
//
//        List<Map> list = new ArrayList();
//        Map map1 = new HashMap();
//        map1.put("name","阳光爸妈");
//        map1.put("setmeal_count",300);
//        map1.put("proportion",0.8888);
//
//        Map map2 = new HashMap();
//        map2.put("name","阳光爸妈");
//        map2.put("setmeal_count",300);
//        map2.put("proportion",0.8888);
//        list.add(map1);
//        list.add(map2);
//
//        map.put("hotSetmeal",list);
//
//        return new Result(true,"查询成功",map);
    }

    //导出报表
    @GetMapping("/exportBusinessReport")
    public void  exportBusinessReport(HttpServletRequest request,HttpServletResponse response){

        try {
            Map<String, Object> map = reportService.getBusinessData();


            //获取到report_template.xlsx的绝对路径
            String realPath = request.getSession().getServletContext().getRealPath("/template" + File.separator + "report_template.xlsx");

            //获取工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(realPath);
            //获取第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取第二行第5个单元格填充日期
            sheet.getRow(2).getCell(5).setCellValue((String) map.get("reportDate"));
            //本日新增会员数
            sheet.getRow(4).getCell(5).setCellValue((int) map.get("todayNewMember"));
            //总会员数
            sheet.getRow(4).getCell(7).setCellValue((int) map.get("totalMember"));
            //本周新增会员数
            sheet.getRow(5).getCell(5).setCellValue((int) map.get("thisWeekNewMember"));
            //本月新增会员数
            sheet.getRow(5).getCell(7).setCellValue((int) map.get("thisMonthNewMember"));

            sheet.getRow(7).getCell(5).setCellValue((int) map.get("todayOrderNumber"));
            sheet.getRow(7).getCell(7).setCellValue((int) map.get("todayVisitsNumber"));
            sheet.getRow(8).getCell(5).setCellValue((int) map.get("thisWeekOrderNumber"));
            sheet.getRow(8).getCell(7).setCellValue((int) map.get("thisWeekVisitsNumber"));
            sheet.getRow(9).getCell(5).setCellValue((int) map.get("thisMonthOrderNumber"));
            sheet.getRow(9).getCell(7).setCellValue((int) map.get("thisMonthVisitsNumber"));

            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");
            int row = 12;
            for (Map o : hotSetmeal) {
                sheet.getRow(row).getCell(4).setCellValue((String) o.get("name"));
                sheet.getRow(row).getCell(5).setCellValue((Long) o.get("setmeal_count"));
                BigDecimal bigDecimal=(BigDecimal) o.get("proportion");
                double x=bigDecimal.doubleValue();
                sheet.getRow(row).getCell(6).setCellValue(x);

                row++;
            }

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=business_report.xlsx");

            //要将excel文件以响应流输出到前台
            workbook.write(response.getOutputStream());
            workbook.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    //导出PDF报表
    @GetMapping("/exportBusinessReport4PDF")
    public void exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response)throws Exception{

        //获取jrxml文件的绝对路径
        String jrxmlPath = request.getSession().getServletContext().getRealPath("template"+File.separator+"health_business3.jrxml");
        //设置japser文件的绝对路径
        String japserPath = request.getSession().getServletContext().getRealPath("template"+File.separator+"health_business3.jasper");
        //编译模板
        JasperCompileManager.compileReportToFile(jrxmlPath,japserPath);

        //准备数据（参数）
        Map<String, Object> map = reportService.getBusinessData();
        //准备数据 （field）
        List list = (List)map.get("hotSetmeal");

        //填充数据
        JasperPrint jasperPrint = JasperFillManager.fillReport(japserPath, map, new JRBeanCollectionDataSource(list));

        response.setContentType("application/pdf");    //告诉浏览器输出的内容是一个二进制流
        response.setHeader("Content-Disposition", "attachment;filename=business_report.pdf");


        //生成报表并输出
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());

    }
}
